/* $Id: SwingUtil.java,v 1.12 2007/10/19 08:16:00 gigabass Exp $
 *
 * Copyright (c) Guido Ludwig. All rights reserved.
 * Use is subject to license terms.
 */
package de.guidoludwig.af;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.URL;
import java.util.logging.Logger;

import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JToolBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.looks.plastic.PlasticLookAndFeel;
import com.jgoodies.looks.windows.WindowsLookAndFeel;

/**
 * SwingUtilities
 * 
 * @author <a href="mailto:jtrade@gigabss.de">Guido Ludwig</a>
 * @version $Revision: 1.12 $
 */
public class SwingUtil {

	/**
	 * set the application's look and feel to JGoodies plastic look and feel
	 * 
	 * @return true if successful
	 */
	public static boolean chooseLookAndFeel() {
		if (isWindows()) {
			try {
				UIManager.setLookAndFeel(new WindowsLookAndFeel());
			} catch (UnsupportedLookAndFeelException e) {
				// ignore, try next
			}
			return true;
		}
		try {
			PlasticLookAndFeel.set3DEnabled(true);
			UIManager.setLookAndFeel(new PlasticLookAndFeel());
			return true;
		} catch (UnsupportedLookAndFeelException e) {
			// silently ignore
			return false;
		}
	}

	public static void finishCurrentEdit() {
		KeyboardFocusManager focusManager = KeyboardFocusManager
				.getCurrentKeyboardFocusManager();
		Component focusOwner = focusManager.getPermanentFocusOwner();
		if (focusOwner == null) {
			return;
		}
		focusManager.clearGlobalFocusOwner();
		focusOwner.requestFocus();
	}

	public static void resizeHook(JComponent component, int height, int width) {
		Dimension preferred = component.getPreferredSize();
		int x = preferred.width * width;
		int y = preferred.height * height;
		if (x == y) {
			return;
		} else if (x > y) {
			preferred.height = preferred.width * height / width;
		} else {
			preferred.width = preferred.height * width / height;
		}
		component.setPreferredSize(preferred);
	}

	/**
	 * @param layout
	 * @return a {@link DefaultFormBuilder} with given layout and the standard
	 *         border for main applications set
	 */
	public static DefaultFormBuilder createBorderedFormBuilder(FormLayout layout) {
		DefaultFormBuilder builder = new DefaultFormBuilder(layout);
		builder.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		return builder;
	}

	/**
	 * @param layout
	 * @return a {@link DefaultFormBuilder} with given layout 
	 */
	public static DefaultFormBuilder createFormBuilder(FormLayout layout) {
		DefaultFormBuilder builder = new DefaultFormBuilder(layout);
		return builder;
	}	
	
	private static boolean isWindows() {
		String osname = System.getProperty("os.name");
		System.out.println("OS : " + osname);
		return osname.toLowerCase().startsWith("win");
		
	}
	public static JButton createToolbarButton(Action action) {
		JToolBar toolbar = new JToolBar();
		return toolbar.add(action);
	}
	public static void main(String[] args) {
		System.out.println(System.getProperties());
	}
	
	public static void runAsThread(Runnable runner) {
		Thread newThread = new Thread(runner);
		newThread.start();
	}
	

    /**
     * Loads an Icon with the given name.
     * The name represents an image source located in the
     * resources/images directory.
     * The name must include the image extension, eg. 'image.gif'
     * <br/>
     * If the image is not found, simply a null Icon is returned !
     * <br/>
     * Possible Exceptions thrown are eaten !
     * If an exception occurs, a null Icon is returned ! 
     * @param name
     * @return the loaded icon or null if the icon could not be loaded
     */
    public static ImageIcon loadIcon(String name) {
        URL url = ClassLoader.getSystemResource("resources/images/" + name); //$NON-NLS-1$
        if (url == null) {
        	Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).warning("icon " + name + "not found"); //$NON-NLS-1$ //$NON-NLS-2$
            return null;
        }
        return new ImageIcon(url);
    }
    
    public static String loadResource(String resource) {
        URL url = ClassLoader.getSystemResource("resources/" + resource);
        StringBuffer buffer = new StringBuffer();
        if (url == null) {
            ErrorMessage.handle(new NullPointerException("URL for resources/" + resource + " not found"));
        } else {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer.toString();
        
    }     
    
    public static String loadFile(String filename) {
        StringBuffer buffer = new StringBuffer();
        RandomAccessFile raf;
		try {
			raf = new RandomAccessFile(filename, "r");
		} catch (FileNotFoundException e) {
			ErrorMessage.handle("File not found", e);
			return null;
		}
		String line = null;
        try {
			while ((line = raf.readLine()) != null) {
			    buffer.append(line + "\n");
			}
		} catch (IOException e) {
			ErrorMessage.handle( e);
			return null;
		}
        return buffer.toString();
        
    }         

}
